<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>分片上传 Demo</title>
		<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
	</head>
	<body>
		<input type="file" id="fileInput" />
		<button onclick="uploads()">上传</button>
		<progress id="progressBar" value="0" max="100"></progress>
	</body>
</html>
<script>
	function uploads() {
		//获取文件信息
		var fileInput = $('#fileInput')[0];
		var file = fileInput.files[0];

		//获取上传对象
		var uploadedFiles = fileInput.files


		if (file) {
			uploadFile(file,uploadedFiles);
		} else {
			// uploadFile(file);
			alert('请检查文件信息');
		}
	}

	function uploadFile(file,uploadedFiles) {
		//设置每个分片大小
		var chunkSize = 1024 * 1024; // 1 MB chunks (adjust as needed)分片最大值

		//分片数
		var chunks = Math.ceil(file.size / chunkSize);
		//初始化上传分片
		var currentChunk = 0;
		var fileName = uploadedFiles[0].name;
		console.log(fileName)

		var uploadNextChunk = function() {
			//把文件进行分片，chunk分片后的文件
			var start = currentChunk * chunkSize;
			var end = (start + chunkSize >= file.size) ? file.size : start + chunkSize;
			var chunk = file.slice(start, end);


			var formData = new FormData();
			formData.append('file', chunk);
			formData.append('chunks', chunks);
			formData.append('currentChunk', currentChunk);
			formData.append('userId', 1);
			formData.append('fileId', 1);
			formData.append('fileName', fileName);
			console.log(formData)

			$.ajax({
				url: "http://127.0.0.1:8089/video/chunk/upload",
				type: "post",
				data: formData,
				processData: false,
				contentType: false,

				xhr: function() {
					var xhr = new window.XMLHttpRequest();
					xhr.upload.addEventListener('progress', function(e) {
						if (e.lengthComputable) {
							var percentComplete = (e.loaded / e.total) * 100;
							$('#progressBar').val(percentComplete);
						}
					}, false);
					return xhr;
				},
				success: function(response) {
					console.log(response)
					currentChunk++;

					if (currentChunk < chunks) {
						// Continue uploading next chunk
						uploadNextChunk();
					} else {
						// Upload completed
						alert('文件上传完毕!');
					}
				},
				error: function(e) {
					alert("网络错误")
				}
			})

		}
		uploadNextChunk()
	}
</script>
